package ink.fujisann.learning.base.configure.swagger;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.util.UriComponentsBuilder;
import springfox.documentation.PathProvider;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.paths.DefaultPathProvider;
import springfox.documentation.spring.web.paths.Paths;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.ArrayList;
import java.util.List;

/**
 * swagger配置类 <br/>
 * 开启swagger2 <br/>
 * 开启knife界面(代替swagger-ui的界面) <br/>
 *
 * @author hulei
 * @date 2020/10/22
 */
@EnableSwagger2WebMvc
@Configuration
public class Swagger {

    @Bean
    public Docket swaggerSpringMvcPlugin() {
        ParameterBuilder lanPara = new ParameterBuilder();
        lanPara
                .name("Accept-Language")
                .description("use lan")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false);

        List<Parameter> pars = new ArrayList<Parameter>();
        pars.add(lanPara.build());

        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("ink.fujisann.learning"))
                .build()
                .globalOperationParameters(pars);
    }

    @Value("${server.servlet.context-path}")
    private String servletContextPath;

    /**
     * 重写 PathProvider ,解决 context-path 重复问题
     *
     * @return PathProvider
     */
    @Bean
    public PathProvider pathProvider() {
        return new DefaultPathProvider() {
            @Override
            public String getOperationPath(String operationPath) {
                operationPath = operationPath.replaceFirst(servletContextPath, "/");
                UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromPath("/");
                return Paths.removeAdjacentForwardSlashes(uriComponentsBuilder.path(operationPath).build().toString());
            }

            @Override
            public String getResourceListingPath(String groupName, String apiDeclaration) {
                apiDeclaration = super.getResourceListingPath(groupName, apiDeclaration);
                return apiDeclaration;
            }
        };
    }
}
